package com.milk.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Functions;
import com.milk.system.common.exception.BusinessException;
import com.milk.system.converter.ProductsConverter;
import com.milk.system.mapper.MerchantsMapper;
import com.milk.system.mapper.ProductsMapper;
import com.milk.system.model.entity.Merchants;
import com.milk.system.model.entity.Products;
import com.milk.system.model.form.ProductsForm;
import com.milk.system.model.query.ProductsPageQuery;
import com.milk.system.model.vo.ProductsPageVO;
import com.milk.system.service.MerchantsService;
import com.milk.system.service.ProductsService;
import jakarta.annotation.Resource;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品信息表服务实现类
 *
 * @author milk
 * @since 2024-05-02
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductsService {

    private final ProductsConverter productsConverter;

    @Resource
    private MerchantsService merchantsService;

    @Resource
    private MerchantsMapper merchantMapper;



    /**
     * 获取商品信息表分页列表
     *
     * @param queryParams 查询参数
     * @return 商品信息表分页列表
     */
    @Override
    public IPage<ProductsPageVO> listPagedProductss(ProductsPageQuery queryParams) {

        // 参数构建
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        LambdaQueryWrapper<Products> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(queryParams.getKeywords()), Products::getProductName, queryParams.getKeywords());

        // 查询数据
        Page<Products> boPage = this.page(new Page<>(pageNum, pageSize), wrapper);

        List<ProductsPageVO> resultVoRecords = new ArrayList<>();

        List<Long> list = boPage.getRecords().stream().map(bo -> bo.getMerchantId()).toList();
        Map<Long, Merchants> merchantIdMap;
        if (CollectionUtils.isNotEmpty(list)){
            List<Merchants> merchants = merchantsService.list(new LambdaQueryWrapper<Merchants>().in(Merchants::getId, list));
            log.info("merchantInfo ---> {}",merchants);
            merchantIdMap = merchants.stream().collect(Collectors.toMap(Merchants::getId, Functions.identity()));
            log.info("merchantIdMap ---> {}",merchantIdMap);
        } else {
            merchantIdMap = null;
        }

        boPage.getRecords().forEach(item ->{
            ProductsPageVO vo = new ProductsPageVO(item);
            if (merchantIdMap.containsKey(item.getMerchantId())){
                vo.setMerchantName(merchantIdMap.get(item.getMerchantId()).getMerchantName());
            }
            resultVoRecords.add(vo);
        });
        IPage<ProductsPageVO> voPage = new Page<>();
        voPage.setCurrent(boPage.getCurrent());
        voPage.setSize(boPage.getSize());
        voPage.setTotal(boPage.getTotal());
        voPage.setRecords(resultVoRecords);
        voPage.setPages(boPage.getPages());
        return voPage;
    }



    /**
     * 获取商品信息表表单数据
     *
     * @param id 商品信息表ID
     * @return
     */
    @Override
    public ProductsForm getProductsFormData(Long id) {
        Products entity = this.getById(id);
        ProductsForm resultVo = new ProductsForm();
        resultVo.setId(entity.getId());
        resultVo.setProductName(entity.getProductName());
        resultVo.setPrice(entity.getPrice());
        resultVo.setStockQuantity(entity.getStockQuantity());

        Merchants merchants = merchantMapper.getMerchantsId(entity.getMerchantId());;
        resultVo.setMerchantName(merchants.getMerchantName());
        resultVo.setDescription(entity.getDescription());
        resultVo.setCategory(entity.getCategory());
        return resultVo;
    }

    /**
     * 新增商品信息表
     *
     * @param formData 商品信息表表单对象
     * @return
     */
    @Override
    public boolean saveProducts(ProductsForm formData) {
        return this.save(getProducts(formData));
    }

    private Products getProducts(ProductsForm formData) {
        Products entity = new Products();
        entity.setProductName(formData.getProductName());
        entity.setPrice(formData.getPrice());
        entity.setStockQuantity(formData.getStockQuantity());
        entity.setDescription(formData.getDescription());
        entity.setCategory(formData.getCategory());
        entity.setUpdatedTime(LocalDateTime.now());
        entity.setProductName(formData.getProductName());
        Merchants merchantInfo = merchantMapper.getMerchantsName(formData.getMerchantName());
        log.info("merchantInfo ---> {}",merchantInfo);
        if (null == merchantInfo){
            throw new BusinessException("商家不存在");
        }
        entity.setMerchantId(merchantInfo.getId());
        entity.setCreatedTime(LocalDateTime.now());
        entity.setDeleted(false);
        entity.setProductImages("");
        log.info("entity--->{}",entity);
        return entity;
    }

    /**
     * 更新商品信息表
     *
     * @param id       商品信息表ID
     * @param formData 商品信息表表单对象
     * @return
     */
    @Override
    public boolean updateProducts(Long id, ProductsForm formData) {
        return this.updateById(getProducts(formData));
    }

    /**
     * 删除商品信息表
     *
     * @param ids 商品信息表ID，多个以英文逗号(,)分割
     * @return true|false
     */
    @Override
    public boolean deleteProductss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的商品信息表数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }


}
